package C036;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: C02
 * Package: C036
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/1/19 23:55
 * @Version 1.0
 * @Since 1.0
 */
public class C02 {
    // 不提交这个类
    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);
        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode2.left = treeNode4;
        treeNode3.right = treeNode5;
        System.out.println(zigzagLevelOrder2(treeNode1));
    }


    public static int intMAXLEN= 2001;
    public static TreeNode[] queue = new TreeNode[intMAXLEN];
    public static int r,l;
    public static List<List<Integer>> zigzagLevelOrder2(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if(root == null) {
            return ans;
        }
        boolean reverse = false;
        queue[0] = root;
        l = 0;
        r = 1;
        int n = 0;
        while(l < r) {
            n = r - l;
            ArrayList<Integer> childAns = new ArrayList<>();
            for (int i = 0, index = reverse ? r - 1 : l, j = reverse ? -1 : 1; i < n; i++, index += j) {
                TreeNode cur  = queue[index];
                childAns.add(cur.val);
            }
            reverse = !reverse;
            for (int i = 0; i < n; i++) {
                TreeNode cur = queue[l++];
                if(cur.left != null) {
                    queue[r] = cur.left;
                    r ++;
                }
                if(cur.right != null) {
                    queue[r] = cur.right;
                    r ++;
                }
            }
            ans.add(childAns);
        }

        return ans;
    }
}
